<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');

// 连接数据库
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "fish";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// 获取上传的图片和模型文件的扩展名
$imageExt = isset($_FILES["model-image"]["name"]) ? pathinfo($_FILES["model-image"]["name"], PATHINFO_EXTENSION) : '';
$modelFileExt = isset($_FILES["model-file"]["name"]) ? pathinfo($_FILES["model-file"]["name"], PATHINFO_EXTENSION) : '';

// 为图片和模型文件生成新的文件名
$newImageName = uniqid() . '.' . $imageExt;
$newModelName = uniqid() . '.' . $modelFileExt;

// 将图片和模型文件移动到指定的文件夹
$uploadDir = 'uploads/';
if (isset($_FILES["model-image"]["tmp_name"])) {
    move_uploaded_file($_FILES["model-image"]["tmp_name"], $uploadDir . $newImageName);
}
if (isset($_FILES["model-file"]["tmp_name"])) {
    move_uploaded_file($_FILES["model-file"]["tmp_name"], $uploadDir . $newModelName);
}

// 获取文件夹路径并拼接网站名称
$website = "https://ringstar.top/api/frond/";
$imagePath = $website . $uploadDir . $newImageName;
$modelPath = $website . $uploadDir . $newModelName;

// 将路径和网站地址存储到数据库
$name = isset($_POST["model-name"]) ? $_POST["model-name"] : '';
$user = isset($_POST["model-user"]) ? $_POST["model-user"] : ''; // 你可以根据需要从前端获取用户信息
$classify = isset($_POST["model-classify"]) ? $_POST["model-classify"] : '';

$sql = "INSERT INTO vuemodel (name, image, glb, user, classify) VALUES ('$name', '$imagePath', '$modelPath', '$user', '$classify')";

if ($conn->query($sql) === TRUE) {
  $response = array('status' => 'success', 'message' => '模型上传成功！');
} else {
  $response = array('status' => 'error', 'message' => '模型上传失败，请重试。');
}

$conn->close();

// 返回响应
echo json_encode($response);
?>
